#include "datamanager.h"
#include "constants.h"
#include <QJsonArray>
#include <QJsonDocument>
#include <QMutexLocker>
#include <QCryptographicHash>

namespace RestaurantSystem {

DataManager* DataManager::s_instance = nullptr;

DataManager::DataManager(QObject* parent)
    : QObject(parent)
    , m_fileHandler(std::make_unique<FileHandler>(this))
    , m_autoSaveTimer(new QTimer(this))
    , m_autoSaveEnabled(true)
    , m_autoSaveInterval(Constants::DATA_SAVE_INTERVAL)
    , m_fileWatcher(new QFileSystemWatcher(this))
    , m_fileWatchingEnabled(true)
    , m_isInitialized(false)
    , m_isShuttingDown(false)
{
    // 设置自动保存定时器
    m_autoSaveTimer->setInterval(m_autoSaveInterval);
    connect(m_autoSaveTimer, &QTimer::timeout, this, &DataManager::onAutoSaveTimer);
    
    // 设置文件监控
    connect(m_fileWatcher, &QFileSystemWatcher::fileChanged, this, &DataManager::onFileChanged);
    
    // 确保数据目录存在
    m_fileHandler->ensureDirectoryExists(Constants::getDataDirectory());
}

DataManager::~DataManager() {
    shutdown();
}

DataManager& DataManager::instance() {
    if (!s_instance) {
        s_instance = new DataManager();
    }
    return *s_instance;
}

bool DataManager::initialize() {
    QMutexLocker locker(&m_mutex);
    
    if (m_isInitialized) {
        return true;
    }
    
    // 加载所有数据
    bool success = true;
    success &= loadData(DataType::USERS);
    success &= loadData(DataType::MENU);
    success &= loadData(DataType::ORDERS);
    success &= loadData(DataType::RATINGS);
    success &= loadData(DataType::CONFIG);
    
    if (success) {
        m_isInitialized = true;
        
        // 启动自动保存
        if (m_autoSaveEnabled) {
            m_autoSaveTimer->start();
        }
        
        // 启动文件监控
        if (m_fileWatchingEnabled) {
            setupFileWatching();
        }
    } else {
        LOG_ERROR("数据管理器初始化失败", "DataManager");
    }
    
    return success;
}

void DataManager::shutdown() {
    QMutexLocker locker(&m_mutex);
    
    if (m_isShuttingDown) {
        return;
    }
    
    m_isShuttingDown = true;
    m_autoSaveTimer->stop();
    
    LOG_INFO("关闭数据管理器", "DataManager");
    
    // 保存所有数据
    saveAll();
    
    m_isInitialized = false;
}

bool DataManager::loadData(DataType dataType) {
    QString filePath = getDataFilePath(dataType);
    QJsonObject data;
    

    
    FileOperationResult result = m_fileHandler->readJsonFile(filePath, data);
    
    if (result == FileOperationResult::FILE_NOT_FOUND) {
        // 文件不存在，初始化默认数据
        initializeDefaultData(dataType);
        return true;
    } else if (result != FileOperationResult::SUCCESS) {
        LOG_ERROR(QString("加载数据失败: %1").arg(fileOperationResultToString(result)), filePath);
        return false;
    }
    
    // 更新缓存
    switch (dataType) {
        case DataType::USERS:
            m_usersCache = CacheItem<QJsonObject>(data);
            break;
        case DataType::MENU:
            m_menuCache = CacheItem<QJsonObject>(data);
            break;
        case DataType::ORDERS:
            m_ordersCache = CacheItem<QJsonObject>(data);
            break;
        case DataType::RATINGS:
            m_ratingsCache = CacheItem<QJsonObject>(data);
            break;
        case DataType::CONFIG:
            m_configCache = CacheItem<QJsonObject>(data);
            break;
    }
    
    return true;
}

bool DataManager::saveData(DataType dataType, bool createBackup) {
    QString filePath = getDataFilePath(dataType);
    QJsonObject data;
    bool isDirty = false;
    
    switch (dataType) {
        case DataType::USERS:
            data = m_usersCache.data;
            isDirty = m_usersCache.isDirty;
            break;
        case DataType::MENU:
            data = m_menuCache.data;
            isDirty = m_menuCache.isDirty;
            break;
        case DataType::ORDERS:
            data = m_ordersCache.data;
            isDirty = m_ordersCache.isDirty;
            break;
        case DataType::RATINGS:
            data = m_ratingsCache.data;
            isDirty = m_ratingsCache.isDirty;
            break;
        case DataType::CONFIG:
            data = m_configCache.data;
            isDirty = m_configCache.isDirty;
            break;
    }
    
    if (!isDirty) {
        return true; // 无需保存
    }
    
    FileOperationResult result = m_fileHandler->writeJsonFile(filePath, data, createBackup);
    
    if (result == FileOperationResult::SUCCESS) {
        // 清除脏标记
        switch (dataType) {
            case DataType::USERS:
                m_usersCache.isDirty = false;
                break;
            case DataType::MENU:
                m_menuCache.isDirty = false;
                break;
            case DataType::ORDERS:
                m_ordersCache.isDirty = false;
                break;
            case DataType::RATINGS:
                m_ratingsCache.isDirty = false;
                break;
            case DataType::CONFIG:
                m_configCache.isDirty = false;
                break;
        }
        
        // 更新文件修改时间记录，避免触发自己的文件变更事件
        if (m_fileWatchingEnabled) {
            QFileInfo fileInfo(filePath);
            m_lastModified[filePath] = fileInfo.lastModified().toMSecsSinceEpoch();
        }
        
        emit dataSaved(dataType, true);
        return true;
    } else {
        LOG_ERROR(QString("保存数据失败: %1").arg(fileOperationResultToString(result)), filePath);
        emit dataSaved(dataType, false);
        return false;
    }
}

QString DataManager::getDataFilePath(DataType dataType) {
    switch (dataType) {
        case DataType::USERS: return Constants::getUsersFilePath();
        case DataType::MENU: return Constants::getMenuFilePath();
        case DataType::ORDERS: return Constants::getOrdersFilePath();
        case DataType::RATINGS: return Constants::getRatingsFilePath();
        case DataType::CONFIG: return Constants::getConfigFilePath();
        default: return QString();
    }
}

void DataManager::initializeDefaultData(DataType dataType) {
    switch (dataType) {
        case DataType::USERS: {
            QJsonObject users;
            users["customers"] = QJsonArray();
            
            // 初始化默认管理员密码 (默认密码: admin123，实际应用中需要用户设置)
            // 注意：这里使用与UserManager相同的加盐哈希算法以确保一致性
            QString saltedPassword = "RestaurantSystem_admin123";
            QByteArray hash = QCryptographicHash::hash(saltedPassword.toUtf8(), QCryptographicHash::Sha256);
            AdminConfig defaultAdmin(hash.toHex()); // admin123的加盐SHA256
            users["admin"] = defaultAdmin.toJson();
            
            m_usersCache = CacheItem<QJsonObject>(users);
            m_usersCache.isDirty = true;
            break;
        }
        case DataType::MENU: {
            QJsonObject menu;
            menu["categories"] = QJsonArray::fromStringList(Constants::DEFAULT_CATEGORIES);
            menu["menuItems"] = QJsonArray();
            
            m_menuCache = CacheItem<QJsonObject>(menu);
            m_menuCache.isDirty = true;
            break;
        }
        case DataType::ORDERS: {
            QJsonObject orders;
            orders["orders"] = QJsonArray();
            
            m_ordersCache = CacheItem<QJsonObject>(orders);
            m_ordersCache.isDirty = true;
            break;
        }
        case DataType::RATINGS: {
            QJsonObject ratings;
            ratings["ratings"] = QJsonArray();
            
            m_ratingsCache = CacheItem<QJsonObject>(ratings);
            m_ratingsCache.isDirty = true;
            break;
        }
        case DataType::CONFIG: {
            QJsonObject config;
            config["version"] = Constants::APP_VERSION;
            config["dataPath"] = Constants::getDataDirectory();
            config["backupEnabled"] = true;
            config["maxBackupFiles"] = Constants::MAX_BACKUP_FILES;
            
            m_configCache = CacheItem<QJsonObject>(config);
            m_configCache.isDirty = true;
            break;
        }
    }
}

void DataManager::markCacheDirty(DataType dataType) {
    switch (dataType) {
        case DataType::USERS:
            m_usersCache.isDirty = true;
            m_usersCache.lastModified = QDateTime::currentDateTime();
            break;
        case DataType::MENU:
            m_menuCache.isDirty = true;
            m_menuCache.lastModified = QDateTime::currentDateTime();
            break;
        case DataType::ORDERS:
            m_ordersCache.isDirty = true;
            m_ordersCache.lastModified = QDateTime::currentDateTime();
            break;
        case DataType::RATINGS:
            m_ratingsCache.isDirty = true;
            m_ratingsCache.lastModified = QDateTime::currentDateTime();
            break;
        case DataType::CONFIG:
            m_configCache.isDirty = true;
            m_configCache.lastModified = QDateTime::currentDateTime();
            break;
    }
}

// ============================================================================
// 用户数据操作实现
// ============================================================================

QList<Customer> DataManager::getAllCustomers() {
    QMutexLocker locker(&m_mutex);
    QList<Customer> customers;
    
    QJsonArray customersArray = m_usersCache.data["customers"].toArray();
    for (const auto& value : customersArray) {
        customers.append(Customer::fromJson(value.toObject()));
    }
    
    return customers;
}

Customer DataManager::getCustomerById(const QString& id) {
    QMutexLocker locker(&m_mutex);
    return getCustomerByIdInternal(id);
}

Customer DataManager::getCustomerByUsername(const QString& username) {
    QMutexLocker locker(&m_mutex);
    return getCustomerByUsernameInternal(username);
}

bool DataManager::addCustomer(const Customer& customer) {
    QMutexLocker locker(&m_mutex);
    
    if (!customer.isValid()) {
        LOG_ERROR("顾客数据无效", customer.getValidationError());
        return false;
    }
    
    // 检查用户名是否已存在（使用内部方法）
    if (getCustomerByUsernameInternal(customer.username).isValid()) {
        LOG_ERROR("用户名已存在", customer.username);
        return false;
    }
    
    // 添加新顾客
    QJsonArray customersArray = m_usersCache.data["customers"].toArray();
    customersArray.append(customer.toJson());
    
    m_usersCache.data["customers"] = customersArray;
    markCacheDirty(DataType::USERS);
    
    emit dataChanged(DataType::USERS, "add", customer.id);
    return true;
}

bool DataManager::updateCustomer(const Customer& customer) {
    QMutexLocker locker(&m_mutex);
    
    if (!customer.isValid()) {
        LOG_ERROR("顾客数据无效", customer.getValidationError());
        return false;
    }
    
    QJsonArray customersArray = m_usersCache.data["customers"].toArray();
    for (int i = 0; i < customersArray.size(); ++i) {
        QJsonObject customerObj = customersArray[i].toObject();
        if (customerObj["id"].toString() == customer.id) {
            customersArray[i] = customer.toJson();
            m_usersCache.data["customers"] = customersArray;
            markCacheDirty(DataType::USERS);
            
            emit dataChanged(DataType::USERS, "update", customer.id);
            return true;
        }
    }
    
    LOG_ERROR("找不到要更新的顾客", customer.id);
    return false;
}

bool DataManager::deleteCustomer(const QString& id) {
    QMutexLocker locker(&m_mutex);
    
    QJsonArray customersArray = m_usersCache.data["customers"].toArray();
    for (int i = 0; i < customersArray.size(); ++i) {
        QJsonObject customerObj = customersArray[i].toObject();
        if (customerObj["id"].toString() == id) {
            customersArray.removeAt(i);
            m_usersCache.data["customers"] = customersArray;
            markCacheDirty(DataType::USERS);
            
            emit dataChanged(DataType::USERS, "delete", id);
            return true;
        }
    }
    
    LOG_ERROR("找不到要删除的顾客", id);
    return false;
}

AdminConfig DataManager::getAdminConfig() {
    QMutexLocker locker(&m_mutex);
    return AdminConfig::fromJson(m_usersCache.data["admin"].toObject());
}

bool DataManager::updateAdminConfig(const AdminConfig& config) {
    QMutexLocker locker(&m_mutex);
    
    if (!config.isValid()) {
        LOG_ERROR("管理员配置无效", "");
        return false;
    }
    
    m_usersCache.data["admin"] = config.toJson();
    markCacheDirty(DataType::USERS);
    
    emit dataChanged(DataType::USERS, "update_admin", "");
    return true;
}

// ============================================================================
// 菜单数据操作实现 (简化实现，其他方法类似)
// ============================================================================

QList<MenuItem> DataManager::getAllMenuItems() {
    QMutexLocker locker(&m_mutex);
    QList<MenuItem> items;
    
    // 检查缓存是否有效
    if (m_menuCache.data.isEmpty()) {
        return items; // 返回空列表
    }
    
    QJsonArray itemsArray = m_menuCache.data["menuItems"].toArray();
    for (const auto& value : itemsArray) {
        items.append(MenuItem::fromJson(value.toObject()));
    }
    
    return items;
}

MenuItem DataManager::getMenuItemById(const QString& id) {
    QMutexLocker locker(&m_mutex);
    
    // 检查缓存是否有效
    if (m_menuCache.data.isEmpty()) {
        return MenuItem(); // 返回无效对象
    }
    
    QJsonArray itemsArray = m_menuCache.data["menuItems"].toArray();
    for (const auto& value : itemsArray) {
        QJsonObject itemObj = value.toObject();
        if (itemObj["id"].toString() == id) {
            return MenuItem::fromJson(itemObj);
        }
    }
    
    return MenuItem(); // 返回无效对象
}

bool DataManager::addMenuItem(const MenuItem& item) {
    QMutexLocker locker(&m_mutex);
    
    if (!item.isValid()) {
        LOG_ERROR("菜品数据无效", item.getValidationError());
        return false;
    }
    
    // 确保缓存有效
    if (m_menuCache.data.isEmpty()) {
        initializeDefaultData(DataType::MENU);
    }
    
    QJsonArray itemsArray = m_menuCache.data["menuItems"].toArray();
    itemsArray.append(item.toJson());
    
    m_menuCache.data["menuItems"] = itemsArray;
    markCacheDirty(DataType::MENU);
    
    emit dataChanged(DataType::MENU, "add", item.id);
    return true;
}

bool DataManager::updateMenuItem(const MenuItem& item) {
    QMutexLocker locker(&m_mutex);
    
    if (!item.isValid()) {
        LOG_ERROR("菜品数据无效", item.getValidationError());
        return false;
    }
    
    // 确保缓存有效
    if (m_menuCache.data.isEmpty()) {
        return false; // 无法更新不存在的数据
    }
    
    QJsonArray itemsArray = m_menuCache.data["menuItems"].toArray();
    bool found = false;
    
    for (int i = 0; i < itemsArray.size(); ++i) {
        QJsonObject itemObj = itemsArray[i].toObject();
        if (itemObj["id"].toString() == item.id) {
            itemsArray[i] = item.toJson();
            found = true;
            break;
        }
    }
    
    if (found) {
        m_menuCache.data["menuItems"] = itemsArray;
        markCacheDirty(DataType::MENU);
        emit dataChanged(DataType::MENU, "update", item.id);
        return true;
    }
    
    return false;
}

bool DataManager::deleteMenuItem(const QString& id) {
    QMutexLocker locker(&m_mutex);
    
    // 确保缓存有效
    if (m_menuCache.data.isEmpty()) {
        return false; // 无法删除不存在的数据
    }
    
    QJsonArray itemsArray = m_menuCache.data["menuItems"].toArray();
    bool found = false;
    
    for (int i = 0; i < itemsArray.size(); ++i) {
        QJsonObject itemObj = itemsArray[i].toObject();
        if (itemObj["id"].toString() == id) {
            itemsArray.removeAt(i);
            found = true;
            break;
        }
    }
    
    if (found) {
        m_menuCache.data["menuItems"] = itemsArray;
        markCacheDirty(DataType::MENU);
        emit dataChanged(DataType::MENU, "delete", id);
        return true;
    }
    
    return false;
}

QStringList DataManager::getMenuCategories() {
    QMutexLocker locker(&m_mutex);
    
    // 确保缓存有效
    if (m_menuCache.data.isEmpty()) {
        initializeDefaultData(DataType::MENU);
    }
    
    QJsonArray categoriesArray = m_menuCache.data["categories"].toArray();
    QStringList categories;
    
    for (const auto& value : categoriesArray) {
        categories.append(value.toString());
    }
    
    return categories;
}

bool DataManager::updateMenuCategories(const QStringList& categories) {
    QMutexLocker locker(&m_mutex);
    
    // 确保缓存有效
    if (m_menuCache.data.isEmpty()) {
        initializeDefaultData(DataType::MENU);
    }
    
    // 更新分类数据
    QJsonArray categoriesArray = QJsonArray::fromStringList(categories);
    m_menuCache.data["categories"] = categoriesArray;
    
    // 标记为脏数据
    markCacheDirty(DataType::MENU);
    
    // 发射数据变更信号
    emit dataChanged(DataType::MENU, "categories_update", "");
    
    return true;
}

// ============================================================================
// 订单数据操作实现 (简化实现)
// ============================================================================

QList<Order> DataManager::getAllOrders() {
    QMutexLocker locker(&m_mutex);
    QList<Order> orders;
    
    QJsonArray ordersArray = m_ordersCache.data["orders"].toArray();
    
    for (const auto& value : ordersArray) {
        orders.append(Order::fromJson(value.toObject()));
    }
    
    return orders;
}

bool DataManager::addOrder(const Order& order) {
    QMutexLocker locker(&m_mutex);
    
    if (!order.isValid()) {
        LOG_ERROR("订单数据无效", order.getValidationError());
        return false;
    }
    
    QJsonArray ordersArray = m_ordersCache.data["orders"].toArray();
    ordersArray.append(order.toJson());
    
    m_ordersCache.data["orders"] = ordersArray;
    markCacheDirty(DataType::ORDERS);
    
    // 立即保存订单数据，确保实时同步
    if (!saveData(DataType::ORDERS)) {
        LOG_ERROR("保存订单数据失败", "DataManager::addOrder");
        return false;
    }
    
    emit dataChanged(DataType::ORDERS, "add", order.id);
    return true;
}

bool DataManager::updateOrder(const Order& order) {
    QMutexLocker locker(&m_mutex);
    
    if (!order.isValid()) {
        LOG_ERROR("订单数据无效", order.getValidationError());
        return false;
    }
    
    QJsonArray ordersArray = m_ordersCache.data["orders"].toArray();
    bool found = false;
    
    for (int i = 0; i < ordersArray.size(); ++i) {
        QJsonObject orderObj = ordersArray[i].toObject();
        if (orderObj["id"].toString() == order.id) {
            ordersArray[i] = order.toJson();
            found = true;
            break;
        }
    }
    
    if (found) {
        m_ordersCache.data["orders"] = ordersArray;
        markCacheDirty(DataType::ORDERS);
        
        // 立即保存订单数据，确保实时同步
        if (!saveData(DataType::ORDERS)) {
            LOG_ERROR("保存订单数据失败", "DataManager::updateOrder");
            return false;
        }
        
        emit dataChanged(DataType::ORDERS, "update", order.id);
        return true;
    }
    
    return false;
}

bool DataManager::deleteOrder(const QString& id) {
    QMutexLocker locker(&m_mutex);
    
    QJsonArray ordersArray = m_ordersCache.data["orders"].toArray();
    bool found = false;
    
    for (int i = 0; i < ordersArray.size(); ++i) {
        QJsonObject orderObj = ordersArray[i].toObject();
        if (orderObj["id"].toString() == id) {
            ordersArray.removeAt(i);
            found = true;
            break;
        }
    }
    
    if (found) {
        m_ordersCache.data["orders"] = ordersArray;
        markCacheDirty(DataType::ORDERS);
        
        // 立即保存订单数据，确保实时同步
        if (!saveData(DataType::ORDERS)) {
            LOG_ERROR("保存订单数据失败", "DataManager::deleteOrder");
            return false;
        }
        
        emit dataChanged(DataType::ORDERS, "delete", id);
        return true;
    }
    
    return false;
}

Order DataManager::getOrderById(const QString& id) {
    QMutexLocker locker(&m_mutex);
    
    QJsonArray ordersArray = m_ordersCache.data["orders"].toArray();
    for (const auto& value : ordersArray) {
        QJsonObject orderObj = value.toObject();
        if (orderObj["id"].toString() == id) {
            return Order::fromJson(orderObj);
        }
    }
    
    // 如果没找到，返回无效订单
    return Order();
}

QList<Order> DataManager::getOrdersByCustomerId(const QString& customerId) {
    QMutexLocker locker(&m_mutex);
    QList<Order> orders;
    
    QJsonArray ordersArray = m_ordersCache.data["orders"].toArray();
    for (const auto& value : ordersArray) {
        QJsonObject orderObj = value.toObject();
        if (orderObj["customerId"].toString() == customerId) {
            orders.append(Order::fromJson(orderObj));
        }
    }
    
    return orders;
}

QList<Order> DataManager::getOrdersByStatus(OrderStatus status) {
    QMutexLocker locker(&m_mutex);
    QList<Order> orders;
    
    QJsonArray ordersArray = m_ordersCache.data["orders"].toArray();
    for (const auto& value : ordersArray) {
        QJsonObject orderObj = value.toObject();
        if (static_cast<OrderStatus>(orderObj["status"].toInt()) == status) {
            orders.append(Order::fromJson(orderObj));
        }
    }
    
    return orders;
}

// ============================================================================
// 评分数据操作实现 (简化实现)
// ============================================================================

QList<Rating> DataManager::getAllRatings() {
    QMutexLocker locker(&m_mutex);
    QList<Rating> ratings;
    
    QJsonArray ratingsArray = m_ratingsCache.data["ratings"].toArray();
    for (const auto& value : ratingsArray) {
        ratings.append(Rating::fromJson(value.toObject()));
    }
    
    return ratings;
}

bool DataManager::addRating(const Rating& rating) {
    QMutexLocker locker(&m_mutex);
    
    if (!rating.isValid()) {
        LOG_ERROR("评分数据无效", rating.getValidationError());
        return false;
    }
    
    QJsonArray ratingsArray = m_ratingsCache.data["ratings"].toArray();
    ratingsArray.append(rating.toJson());
    
    m_ratingsCache.data["ratings"] = ratingsArray;
    markCacheDirty(DataType::RATINGS);
    
    emit dataChanged(DataType::RATINGS, "add", rating.id);
    return true;
}

bool DataManager::updateRating(const Rating& rating) {
    QMutexLocker locker(&m_mutex);
    
    if (!rating.isValid()) {
        LOG_ERROR("评分数据无效", rating.getValidationError());
        return false;
    }
    
    QJsonArray ratingsArray = m_ratingsCache.data["ratings"].toArray();
    bool found = false;
    
    for (int i = 0; i < ratingsArray.size(); ++i) {
        QJsonObject ratingObj = ratingsArray[i].toObject();
        if (ratingObj["id"].toString() == rating.id) {
            ratingsArray[i] = rating.toJson();
            found = true;
            break;
        }
    }
    
    if (!found) {
        LOG_ERROR("未找到要更新的评分", rating.id);
        return false;
    }
    
    m_ratingsCache.data["ratings"] = ratingsArray;
    markCacheDirty(DataType::RATINGS);
    
    emit dataChanged(DataType::RATINGS, "update", rating.id);
    return true;
}

bool DataManager::deleteRating(const QString& id) {
    QMutexLocker locker(&m_mutex);
    
    QJsonArray ratingsArray = m_ratingsCache.data["ratings"].toArray();
    bool found = false;
    
    for (int i = 0; i < ratingsArray.size(); ++i) {
        QJsonObject ratingObj = ratingsArray[i].toObject();
        if (ratingObj["id"].toString() == id) {
            ratingsArray.removeAt(i);
            found = true;
            break;
        }
    }
    
    if (!found) {
        LOG_ERROR("未找到要删除的评分", id);
        return false;
    }
    
    m_ratingsCache.data["ratings"] = ratingsArray;
    markCacheDirty(DataType::RATINGS);
    
    emit dataChanged(DataType::RATINGS, "delete", id);
    return true;
}

// ============================================================================
// 统计数据实现
// ============================================================================

Statistics DataManager::generateStatistics() {
    Statistics stats;
    
    // 生成库存统计
    stats.stockInfos = getStockStatistics();
    
    // 生成销量统计
    stats.salesInfos = getSalesStatistics();
    
    // 生成评分统计
    stats.overallRating = getRatingStatistics();
    
    return stats;
}

QList<Statistics::StockInfo> DataManager::getStockStatistics() {
    QList<Statistics::StockInfo> stockInfos;
    QList<MenuItem> items = getAllMenuItems();
    
    for (const MenuItem& item : items) {
        Statistics::StockInfo info;
        info.menuItemId = item.id;
        info.menuItemName = item.name;
        info.currentStock = item.stock;
        info.lowStockThreshold = Constants::LOW_STOCK_THRESHOLD;
        stockInfos.append(info);
    }
    
    return stockInfos;
}

QList<Statistics::SalesInfo> DataManager::getSalesStatistics() {
    QList<Statistics::SalesInfo> salesInfos;
    QList<MenuItem> items = getAllMenuItems();
    
    for (const MenuItem& item : items) {
        Statistics::SalesInfo info;
        info.menuItemId = item.id;
        info.menuItemName = item.name;
        info.totalSales = item.salesCount;
        info.totalRevenue = item.salesCount * item.price;
        salesInfos.append(info);
    }
    
    return salesInfos;
}

Statistics::RatingInfo DataManager::getRatingStatistics() {
    Statistics::RatingInfo info;
    QList<Rating> ratings = getAllRatings();
    
    if (ratings.isEmpty()) {
        info.averageRating = 0.0;
        info.totalRatings = 0;
        info.ratingDistribution = {0, 0, 0, 0, 0}; // 1-5星的分布
        return info;
    }
    
    info.totalRatings = ratings.size();
    info.ratingDistribution = {0, 0, 0, 0, 0};
    
    double totalRating = 0.0;
    for (const Rating& rating : ratings) {
        totalRating += rating.rating;
        if (rating.rating >= 1 && rating.rating <= 5) {
            info.ratingDistribution[rating.rating - 1]++;
        }
    }
    
    info.averageRating = totalRating / info.totalRatings;
    
    return info;
}

// ============================================================================
// 缓存和数据同步实现
// ============================================================================

bool DataManager::saveAll() {
    QMutexLocker locker(&m_mutex);
    
    bool success = true;
    // 自动保存不创建备份，减少文件冗余
    success &= saveData(DataType::USERS, false);
    success &= saveData(DataType::MENU, false);
    success &= saveData(DataType::ORDERS, false);
    success &= saveData(DataType::RATINGS, false);
    success &= saveData(DataType::CONFIG, false);
    
    if (!success) {
        LOG_ERROR("部分数据保存失败", "DataManager");
    }
    
    return success;
}

bool DataManager::saveAllWithBackup() {
    QMutexLocker locker(&m_mutex);
    
    bool success = true;
    // 重要操作创建备份，只有用户数据需要备份
    success &= saveData(DataType::USERS, true);  // 只为用户数据创建备份
    success &= saveData(DataType::MENU, false);
    success &= saveData(DataType::ORDERS, false);
    success &= saveData(DataType::RATINGS, false);
    success &= saveData(DataType::CONFIG, false);
    
    if (!success) {
        LOG_ERROR("部分数据保存失败", "DataManager");
    }
    
    return success;
}

bool DataManager::reloadAll() {
    QMutexLocker locker(&m_mutex);
    
    bool success = true;
    success &= loadData(DataType::USERS);
    success &= loadData(DataType::MENU);
    success &= loadData(DataType::ORDERS);
    success &= loadData(DataType::RATINGS);
    success &= loadData(DataType::CONFIG);
    
    return success;
}

void DataManager::clearCache() {
    QMutexLocker locker(&m_mutex);
    
    m_usersCache = CacheItem<QJsonObject>();
    m_menuCache = CacheItem<QJsonObject>();
    m_ordersCache = CacheItem<QJsonObject>();
    m_ratingsCache = CacheItem<QJsonObject>();
    m_configCache = CacheItem<QJsonObject>();
}

void DataManager::performAutoSave() {
    if (!m_isInitialized || m_isShuttingDown) {
        return;
    }
    
    // 每次自动保存时也检查文件是否有外部变更（作为备用机制）
    checkForExternalChanges();
    
    saveAll();
}

void DataManager::checkForExternalChanges() {
    QStringList filesToCheck = {
        getDataFilePath(DataType::USERS),
        getDataFilePath(DataType::MENU),
        getDataFilePath(DataType::ORDERS),
        getDataFilePath(DataType::RATINGS),
        getDataFilePath(DataType::CONFIG)
    };
    
    for (const QString& filePath : filesToCheck) {
        if (QFile::exists(filePath) && isExternalFileChange(filePath)) {
            onFileChanged(filePath);
        }
    }
}

void DataManager::onAutoSaveTimer() {
    performAutoSave();
}

void DataManager::setAutoSaveInterval(int intervalMs) {
    m_autoSaveInterval = intervalMs;
    m_autoSaveTimer->setInterval(intervalMs);
}

void DataManager::setAutoSaveEnabled(bool enabled) {
    m_autoSaveEnabled = enabled;
    if (enabled && m_isInitialized) {
        m_autoSaveTimer->start();
    } else {
        m_autoSaveTimer->stop();
    }
}

void DataManager::setFileWatchingEnabled(bool enabled) {
    m_fileWatchingEnabled = enabled;
    if (enabled && m_isInitialized) {
        setupFileWatching();
    } else if (!enabled) {
        // 清除监控的文件
        QStringList files = m_fileWatcher->files();
        if (!files.isEmpty()) {
            m_fileWatcher->removePaths(files);
        }
        m_lastModified.clear();
    }
}

void DataManager::setupFileWatching() {
    // 添加需要监控的数据文件
    QStringList filesToWatch = {
        getDataFilePath(DataType::USERS),
        getDataFilePath(DataType::MENU),
        getDataFilePath(DataType::ORDERS),
        getDataFilePath(DataType::RATINGS),
        getDataFilePath(DataType::CONFIG)
    };
    
    for (const QString& filePath : filesToWatch) {
        if (QFile::exists(filePath)) {
            m_fileWatcher->addPath(filePath);
            // 记录当前文件的修改时间
            QFileInfo fileInfo(filePath);
            m_lastModified[filePath] = fileInfo.lastModified().toMSecsSinceEpoch();
        }
    }
}

bool DataManager::isExternalFileChange(const QString& filePath) {
    QFileInfo fileInfo(filePath);
    qint64 currentModified = fileInfo.lastModified().toMSecsSinceEpoch();
    qint64 lastModified = m_lastModified.value(filePath, 0);
    
    // 如果文件修改时间发生变化，且距离上次记录时间超过100ms，认为是外部变更
    // 100ms的间隔是为了避免本进程保存文件时触发重复加载
    return (currentModified > lastModified + 100);
}

void DataManager::onFileChanged(const QString& path) {
    if (!m_isInitialized || m_isShuttingDown || !m_fileWatchingEnabled) {
        return;
    }
    
    if (!isExternalFileChange(path)) {
        // 不是外部变更，忽略
        return;
    }
    
    // 确定数据类型
    DataType dataType;
    if (path == getDataFilePath(DataType::USERS)) {
        dataType = DataType::USERS;
    } else if (path == getDataFilePath(DataType::MENU)) {
        dataType = DataType::MENU;
    } else if (path == getDataFilePath(DataType::ORDERS)) {
        dataType = DataType::ORDERS;
    } else if (path == getDataFilePath(DataType::RATINGS)) {
        dataType = DataType::RATINGS;
    } else if (path == getDataFilePath(DataType::CONFIG)) {
        dataType = DataType::CONFIG;
    } else {
        return; // 未知文件，忽略
    }
    
    // 延迟重新加载，避免文件写入过程中的读取错误
    QTimer::singleShot(200, this, [this, dataType, path]() {
        QMutexLocker locker(&m_mutex);
        
        // 重新加载数据
        if (loadData(dataType)) {
            emit externalFileChanged(dataType, path);
        } else {
            LOG_ERROR(QString("重新加载数据失败: %1").arg(static_cast<int>(dataType)), "DataManager::onFileChanged");
        }
        
        // 更新文件修改时间记录
        QFileInfo fileInfo(path);
        m_lastModified[path] = fileInfo.lastModified().toMSecsSinceEpoch();
        
        // 重新添加文件监控（QFileSystemWatcher在文件变更后可能会移除监控）
        if (!m_fileWatcher->files().contains(path)) {
            m_fileWatcher->addPath(path);
        }
    });
}

// 注意：这里省略了一些方法的实现以控制篇幅，
// 实际项目中需要实现所有在头文件中声明的方法

// ========================================================================
// 内部方法实现（不加锁）
// ========================================================================

Customer DataManager::getCustomerByUsernameInternal(const QString& username) {
    QJsonArray customersArray = m_usersCache.data["customers"].toArray();
    for (const auto& value : customersArray) {
        QJsonObject customerObj = value.toObject();
        if (customerObj["username"].toString() == username) {
            return Customer::fromJson(customerObj);
        }
    }
    return Customer(); // 返回无效对象
}

Customer DataManager::getCustomerByIdInternal(const QString& id) {
    QJsonArray customersArray = m_usersCache.data["customers"].toArray();
    for (const auto& value : customersArray) {
        QJsonObject customerObj = value.toObject();
        if (customerObj["id"].toString() == id) {
            return Customer::fromJson(customerObj);
        }
    }
    return Customer(); // 返回无效对象
}

bool DataManager::updateCustomerInternal(const Customer& customer) {
    if (!customer.isValid()) {
        LOG_ERROR("顾客数据无效", customer.getValidationError());
        return false;
    }
    
    QJsonArray customersArray = m_usersCache.data["customers"].toArray();
    for (int i = 0; i < customersArray.size(); ++i) {
        QJsonObject customerObj = customersArray[i].toObject();
        if (customerObj["id"].toString() == customer.id) {
            customersArray[i] = customer.toJson();
            m_usersCache.data["customers"] = customersArray;
            markCacheDirty(DataType::USERS);
            emit dataChanged(DataType::USERS, "update", customer.id);
            return true;
        }
    }
    
    LOG_ERROR("顾客不存在", customer.id);
    return false;
}

} // namespace RestaurantSystem
